package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


import java.util.Date;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.InventoryClassDao;
import com.ruoyi.business.domain.InventoryClass;
import com.ruoyi.business.service.IInventoryClassService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * InventoryClassService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-06-22
 */
@Transactional(readOnly = true)
@Service
public class InventoryClassServiceImpl implements IInventoryClassService {

    @Autowired
    private InventoryClassDao inventoryClassDao;

    /**
     * 查询InventoryClass
     *
     * @param cinvccode InventoryClassID
     * @return InventoryClass
     */
    @Override
    public InventoryClass findById(String cinvccode) {
        return inventoryClassDao.findById(cinvccode).get();
    }

    /**
     * 分页查询InventoryClass列表
     *
     * @param req InventoryClass
     * @return InventoryClass
     */
    @Override
    public Page<InventoryClass> findInventoryClassPage(InventoryClass req) {
        Specification<InventoryClass> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Optional.ofNullable(pageDomain.getOrderByColumn()).map(Sort::by).orElse(Sort.by("iinvcgrade").ascending().and(Sort.by("cinvccode").ascending())));

        Page<InventoryClass> page = inventoryClassDao.findAll(example, pageable);
         List<InventoryClass>   list= page.getContent();
         for(InventoryClass inventoryClass:list){
             String cinvcode=inventoryClass.getCinvccode();
             Integer igrade= inventoryClass.getIinvcgrade();
             if(!inventoryClass.getBinvcend()){
                 List<InventoryClass>  childlist=inventoryClassDao.getInventoryClassesByCinvccodeStartsWithAndIinvcgrade(cinvcode,igrade+1);
                 childlist=childlist.stream().filter(obj->obj.getCinvccode().compareTo("02003001")>0 && obj.getCinvccode().compareTo("02003006")<=0).collect(Collectors.toList());
                 inventoryClass.setChildren(childlist);
             }
             //树形结构2-3-3-3
             if(cinvcode.length()==2){
                 inventoryClass.setParent(null);
             }else if(cinvcode.length()==5){
                 inventoryClass.setParent(null);
             }else if(cinvcode.length()==8){
                 inventoryClass.setParent(inventoryClassDao.findById(cinvcode.substring(0,5)).orElse(null));
             }else if(cinvcode.length()==11){
                 inventoryClass.setParent(inventoryClassDao.findById(cinvcode.substring(0,8)).orElse(null));
             }

         }
        return page;
    }

    /**
     * 分页查询InventoryClass列表
     *
     * @param req InventoryClass
     * @return InventoryClass
     */
    @Override
    public List<InventoryClass> findInventoryClassList(InventoryClass req) {
        Specification<InventoryClass> example = formatQueryParams(req);
        List<InventoryClass> list = inventoryClassDao.findAll(example, Sort.by(Sort.Direction.DESC,"createTime"));
        return list;
    }

    private Specification<InventoryClass> formatQueryParams(InventoryClass req){
        Specification<InventoryClass> example = new Specification<InventoryClass>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<InventoryClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(req.getCinvccode())){
                    Predicate pre = cb.equal(root.get("cinvccode").as(String.class), req.getCinvccode());
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getCinvcname())){
                    Predicate pre = cb.like(root.get("cinvcname").as(String.class), "%" + req.getCinvcname()+ "%");
                    list.add(pre);
                }
                if (null != req.getIinvcgrade()){
                    Predicate pre = cb.equal(root.get("iinvcgrade").as(Integer.class), req.getIinvcgrade());
                    list.add(pre);
                }
                if (null != req.getBinvcend()){
                    Predicate pre = cb.equal(root.get("binvcend").as(Integer.class), req.getBinvcend());
                    list.add(pre);
                }
                Predicate pre1 =  cb.equal(root.get("cinvccode").as(String.class), "02003");
                list.add(pre1);


                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）InventoryClass
     *
     * @param inventoryClass InventoryClass
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(InventoryClass inventoryClass) {
        inventoryClassDao.save(inventoryClass);
    }


    /**
     * 批量删除InventoryClass
     *
     * @param cinvccodes 需要删除的InventoryClassID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<String> cinvccodes) {
        List<InventoryClass> existBeans = inventoryClassDao.findAllById(cinvccodes);
        if(!existBeans.isEmpty()){
            inventoryClassDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除InventoryClass信息
     *
     * @param cinvccode InventoryClassID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteInventoryClassById(String cinvccode) {
         inventoryClassDao.deleteById(cinvccode);
    }
}
